package com.mystyle.le.weekproject.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 将图片保存到SD卡上
 * Created by le on 2016/10/9.
 */
public class FileUtils {

    //获取SD的存储路径
    public static final String PATH = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS) + File.separator;

    //判断是否挂载
    public static boolean isMounted(){
        String state = Environment.getExternalStorageState();//确认SD卡的状态
        return state.equals(Environment.MEDIA_MOUNTED);
    }
    //公共目录存图片
    /**
     * 参数1：图片的路径，网址
     * 参数2：图片每次读取的大小
     * @param path
     * @param buf
     */
    public static void saveImage(String path,byte[] buf){
        //判断SD卡是否挂载
        if(!isMounted()){
            return;
        }
        //获取当前文件目录
        File file = new File(PATH);
        //判断当前目录是否存在，如果不存在，创建
        if(!file.exists()){
            file.mkdir();
        }
        //存在就读取文件
        try {
            FileOutputStream stream = new FileOutputStream(new File(file, getImageName(path)));
            stream.write(buf);
            stream.flush();
            stream.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 取图片
     *
     * 参数：图片的路径
     * @param
     * @return
     */
    public static Bitmap readImg(String imgPath){
        if(!isMounted()){
            return null;
        }

        File file = new File(PATH, getImageName(imgPath));
        if(file.exists()){
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            return bitmap;
        }
        return null;

    }

    /**
     * 清除SD卡里缓存目录下的所有数据
     * @param
     * @return
     */

    public static void clearData(){
        if(!isMounted()){
            return;
        }else{
            File file = new File(PATH);
            //判断文件是否存在
            if(file.exists()){
                File[] files = file.listFiles();
                for(File file1:files){
                    file1.delete();//删除文件
                }
            }
        }
    }
    /**
     * 截取图片名字
     * @param name
     * @return
     */
    public static String getImageName(String name){
        return name.substring(name.lastIndexOf("/")+1);
    }

}
